package org.springblade.common.tool;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Objects;

/**
 * @ClassName DownloadUtil
 * @Description
 * @Author zhang_xfei
 * @DATE 2020 2020/6/5 14:53
 **/
public class DownloadUtil {
	public static void setDownloadFileName(String name, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		String userAgent = request.getHeader("User-Agent");
		if (null == userAgent || -1 == userAgent.indexOf("MSIE") && -1 == userAgent.indexOf("Trident") && -1 == userAgent.indexOf("Edge")) {
			name = new String(name.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
		} else {
			name = URLEncoder.encode(name, "UTF8");
		}

		response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", name));
		response.setContentType("application/octet-stream");
		response.setCharacterEncoding("UTF-8");
	}

	public static String imageToBase64(String imgPath) {
		byte[] data = null;
		// 读取图片字节数组
		try {
			InputStream in = new FileInputStream(imgPath);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 对字节数组Base64编码
		Base64.Encoder encoder = Base64.getEncoder();
		// 返回Base64编码过的字节数组字符串
		return encoder.encodeToString(data);
	}


}
